﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DataMongo;
using Google.GData.Client;
using MongoDB.Bson;
using DataMongo.Entities;

using MVCMongo.Services;
using WebMatrix.WebData;

namespace MVCMongo.Controllers
{
    public class FeedsCommentController : ApiController
    {
        private string fbBaseUrl = "http://www.facebook.com/sharer.php?u=";
        private string twitterUrl = "http://twitter.com/home?status=";
        public dynamic GetPosts(int feedtype, int CategoryId)
        {

            var connection = new RepositoryBaseMongo("UserPost");
            var fc = new RepositoryBaseMongo("FeedComment");
            var userid = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
            var feedconnection = new RepositoryBaseMongo("FeedPost");
            var userconnection = new RepositoryBaseMongo("Users");
            var shareconnection = ConfigurationManager.AppSettings["ShareLinkUrl"].ToString() + "/Feed/";
            List<FeedPost> feedlist = new List<FeedPost>();
            if (feedtype == 1 || feedtype==2)
            {
                feedlist = feedconnection.GetAll<FeedPost>().Where(x=>x.PostType!="submit" && x.PostType!="submitUrl").OrderByDescending(x => x.FeedPostId).ToList();
            }
            if (feedtype == 3)
            {
                feedlist = feedconnection.GetAll<FeedPost>().OrderByDescending(x => x.NumberofViews).ToList();
            }
            if (feedtype == 4)
            {
                feedlist = feedconnection.GetAll<FeedPost>().Where(x => x.IsUpcoming).ToList();
            }
            if (feedtype == 5)
            {
                feedlist = feedconnection.GetAll<FeedPost>().Where(x => x.CategoryId==CategoryId).ToList();
            }
            if (feedtype == 6)
            {
                feedlist = feedconnection.GetAll<FeedPost>().Where(x => x.PostType == "submit").ToList();
            }
            if (feedtype == 7)
            {
                feedlist = feedconnection.GetAll<FeedPost>().Where(x => x.PostType == "submitUrl").ToList();
            }
            var ret = (from feed in feedlist
                       orderby feed.FeedPostId descending
                       select new
                       {
                           Imageurl = ConfigurationManager.AppSettings["ImageLinkUrl"] +feed.ImageURL1,
                           Title = feed.Title,
                           SourceId = UtilityService.GetSourceNameById(feed.SourceId),
                           ShortDescription = feed.ShortDescription,
                           FeedId = feed.FeedPostId,
                           LikeCount=UtilityService.GetFeedLikeCount(feed.FeedPostId),
                           LikeOrUnlike=UtilityService.GetLikeOrUnlike(feed.FeedPostId),
                           PostedDate= feed.PublishDate,
                           LinkUrl = "/Feed/" + feed.FeedPostId + "/" + UtilityService.RemoveSpecialCharacters(feed.Title),
                           FbShareLink ="javascript:popup_share('"+fbBaseUrl + shareconnection + feed.FeedPostId + "/" + feed.Title.Replace("'", "`")+ "&t=Share',800,320)",
                           TwitterShareLink = "javascript:popup_share('" + twitterUrl + shareconnection + feed.FeedPostId + "/" + feed.Title.Replace("'", "`")+ "',800,320)",
                           PostComments = (from comment in fc.GetAll<FeedComment>()
                                           join userimagecomment in userconnection.GetAll<Users>().ToList() on comment.UserId equals userimagecomment.UserId
                                           where comment.FeedId == feed.FeedPostId
                                           orderby comment.CommentedOn descending 
                                           select new
                                           {
                                               CommentedBy = comment.Name,
                                               CommentedByAvatar = "/Content/UserProfile/User/" + userimagecomment.ImageUrl,
                                               CommentedOn = comment.CommentedOn,
                                               CommentId = comment.CommentId,
                                               Description = comment.Description,
                                               FeedId = comment.FeedId,
                                           }).Take(2).OrderBy(x=>x.CommentId),
                           CommentCount = "Comment ( "+ UtilityService.GetCommentCount(feed.FeedPostId)+" )"
                                           
                       }).AsEnumerable();
            return ret.Take(30); 

        }

    

        public HttpResponseMessage PostPostComment(FeedComment feedComment)
        {
            var ConnectionUser = new RepositoryBaseMongo("Users");
            var currentUser = (from u in ConnectionUser.GetAll<Users>()
                where u.UserId == WebSecurity.CurrentUserId
                select u).ToList();
            Users user = new Users();
            if (currentUser.Count > 0) user = currentUser[0];

            feedComment.CommentedOn = DateTime.UtcNow;

            var connection = new RepositoryBaseMongo("FeedComment");
            var Feedcomments = connection.GetAll<FeedComment>().ToList();
            int Id = 0;
            if (Feedcomments.Any())
                Id = Feedcomments.Max(x => x.CommentId);
            Id += 1;
            feedComment.CommentId = Id;
            feedComment.Name = UtilityService.GetCurrentUserFullName(WebSecurity.CurrentUserId);
            feedComment.UserId = WebSecurity.CurrentUserId;
            connection.InsertOrUpdate(feedComment);
            var ret = new
            {
                CommentedBy = feedComment.Name,
                CommentedByAvatar = "/Content/UserProfile/User/" + user.ImageUrl,
                CommentedOn = feedComment.CommentedOn,
                CommentId = feedComment.CommentId,
                Description = feedComment.Description,
                FeedId = feedComment.FeedId
            };

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ret);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = feedComment.CommentId }));
                return response;
            }
           
        

        // PUT api/Comment/5
        public HttpResponseMessage PutPostComment(int id, PostComment postcomment)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != postcomment.CommentId)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

         
            return Request.CreateResponse(HttpStatusCode.OK);
        }

    }
}